package cn.wostore.wxhelper.utils;

import android.content.ContentValues;
import cn.wostore.wxhelper.WxHelperApp;
import net.sqlcipher.Cursor;
import net.sqlcipher.database.SQLiteDatabase;

/**
 * @author wuch
 * @date 2018/12/29 0029
 */
public class DaoHandler {

    private static final String TAG = DaoHandler.class.getSimpleName();

    private MyDatabaseHelper helper;

    private DaoHandler() {
        L.d(TAG, "DaoHandler create "+WxHelperApp.getInstance());
        helper = new MyDatabaseHelper(WxHelperApp.getInstance());
        L.d(TAG, "DaoHandler created "+helper);
    }

    private static DaoHandler instance = new DaoHandler();

    public static DaoHandler getInstance() {
        L.d(TAG, "getInstance: instance = "+instance);
        return instance;
    }

    public Cursor query(String table, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        SQLiteDatabase readableDatabase = helper.getReadableDatabase("");
        Cursor cursor = readableDatabase.query(table, projection, selection, selectionArgs, null, null, sortOrder);
        L.d(TAG, "query data from "+table+", count: "+cursor.getCount());
        return cursor;
    }

    public void insert(String table, String nullColumnHack, ContentValues values) {
        L.d(TAG,"insert "+values.toString()+" to "+table);
        SQLiteDatabase writableDatabase = helper.getWritableDatabase("");
        writableDatabase.insert(table, nullColumnHack, values);
    }

    public void update(String table, ContentValues values, int id) {
        L.d(TAG, "update "+values.toString()+" of column "+id+" in "+table);
        SQLiteDatabase writableDatabase = helper.getWritableDatabase("");
        writableDatabase.update(table, values, "forwardRuleId=?", new String[]{Integer.toString(id)});
    }

    public void delete(String table, int id) {
        L.d(TAG,"delete column "+id+" in "+table);
        SQLiteDatabase writableDatabase = helper.getWritableDatabase("");
        writableDatabase.delete(table, "forwardRuleId=?", new String[]{Integer.toString(id)});
    }

}
